package com.shxy.rlzy.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shxy.rlzy.common.lang.Result;
import com.shxy.rlzy.entity.Depart;
import com.shxy.rlzy.service.IDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tanhao
 * @since 2021-09-23
 */
@RestController
@RequestMapping("/depart")
public class DepartController extends BaseController {
    private IDepartService departService;

    @Autowired
    public void setDepartService(IDepartService departService) {
        this.departService = departService;
    }


    /**
     * 获取部门列表
     * @return
     */
    @GetMapping(value = {"/list"})
    public Result list(@RequestParam(name = "bonus", defaultValue = "false") boolean hasBonus) {
        // 获取部门列表
        List<Depart> departs = departService.list();
        // 过滤出参与绩效分配的部门
        if(hasBonus) {
            departs = departs.stream().filter(Depart::isHasBonus).toList();
        }
        // 返回结果
        return Result.succ(departs);
    }

    /**
     * 保存部门信息
     * @return
     */
    @PutMapping("/save")
    public Result save(@RequestBody Depart depart) {
        // 判断该部门信息是否已存在
        boolean ext = departService.exist(depart);
        if(ext) {
            return Result.fail("该部门已存在");
        }
        boolean rs = departService.saveOrUpdate(depart);
        if(rs) {
            return Result.succ("保存部门信息成功！");
        }
        return Result.fail("保存部门信息失败！");
    }

    /**
     * 删除部门
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        // 删除部门
        boolean rs = departService.deleteDepartById(id);
        if(rs) {
            return Result.succ("删除成功!");
        }
        return Result.fail("删除失败!");
    }

    @GetMapping("/items")
    public Result items() {
        List<JSONObject> list = departService.list().stream().map(depart -> {
            JSONObject obj = JSONUtil.createObj();
            obj.set("id", depart.getId());
            obj.set("name", depart.getName());
            return obj;
        }).toList();
        return Result.succ(list);
    }
}
